package com.moyun.modelclass.adapter;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.moyun.modelclass.activity.LoginVerificationCodeActivity;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.CheckCollectListUserApi;
import com.moyun.modelclass.http.api.CheckFollowListUserApi;
import com.moyun.modelclass.http.bean.ArticleResponse;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.DataUtil;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * 首页：s搜索结果
 */
public class SearchResultAdapter extends BaseQuickAdapter<ArticleResponse, BaseViewHolder> {
    private OnFindClick onFindClick;
    protected MMKV kv;

    private List<CheckFollowListUserApi.BeanInfo> mUserFollowList = new ArrayList<>();
    private CheckFollowListUserApi.BeanInfo UserFollow = new CheckFollowListUserApi.BeanInfo();
    private List<CheckCollectListUserApi.BeanInfo> mUserArticleList = new ArrayList<>();
    private CheckCollectListUserApi.BeanInfo articleCollect = new CheckCollectListUserApi.BeanInfo();

    private Drawable collectYes = null, collectNot = null;

    public void setOnFindClick(OnFindClick onFindClick) {
        this.onFindClick = onFindClick;
        UserFollow.setFollow(true);
        articleCollect.setLikes(true);
    }

    public SearchResultAdapter() {
        super(R.layout.item_home_find);
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        kv = MMKV.defaultMMKV();
        collectYes = ContextCompat.getDrawable(getContext(), R.drawable.icon_collect_yes);
        collectNot = ContextCompat.getDrawable(getContext(), R.drawable.icon_collect_not);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, ArticleResponse beanInfo) {
        //头像
        ImageView headPortrait = baseViewHolder.getView(R.id.iv_home_find_head_portrait);
        Glide.with(getContext())
                .asBitmap()
                .load(CommonConfiguration.splitResUrl(3, beanInfo.getUserInfo().getAvatar()))
                .placeholder(R.drawable.icon_head_portrait)
                .error(R.drawable.icon_head_portrait)
                .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                .into(new BitmapImageViewTarget(headPortrait) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        headPortrait.setImageBitmap(ImageUtils.toRound(resource));
                    }
                });

        baseViewHolder.setText(R.id.tv_home_find_name, beanInfo.getUserInfo().getNickName());
        baseViewHolder.setText(R.id.tv_home_find_title, beanInfo.getUserInfo().getDesc());
        baseViewHolder.setText(R.id.tv_home_find_article_title, beanInfo.getTitle());

        if (beanInfo.getSummary().isEmpty()) {
            baseViewHolder.setGone(R.id.tv_home_find_article_details, true);
        } else {
            baseViewHolder.setGone(R.id.tv_home_find_article_details, false);
            baseViewHolder.setText(R.id.tv_home_find_article_details, beanInfo.getSummary());
        }

        //文章图片
        ImageView articleImage = baseViewHolder.getView(R.id.iv_home_find_image);

        Glide.with(getContext())
                .asBitmap()
                .load(CommonConfiguration.splitResUrl(5, beanInfo.getSimpleImage()))
                .centerInside()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(new BitmapImageViewTarget(articleImage) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        articleImage.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                    }
                });

        StringBuilder tags = new StringBuilder();
        if (beanInfo.getTags() != null && beanInfo.getTags().size() > 0) {
            baseViewHolder.setVisible(R.id.tv_home_find_subject, true);
            for (int i = 0; i < beanInfo.getTags().size(); i++) {
                //证明是最后一个
                if (i == beanInfo.getTags().size() - 1) {
                    tags.append("#").append(beanInfo.getTags().get(i));
                } else {
                    tags.append("#").append(beanInfo.getTags().get(i)).append("，");
                }
            }
        } else {
            baseViewHolder.setVisible(R.id.tv_home_find_subject, false);
        }

        baseViewHolder.setText(R.id.tv_home_find_subject, tags);
        baseViewHolder.setText(R.id.tv_home_find_time, DataUtil.getTimeShowString(TimeUtils.string2Millis(beanInfo.getUpdateTime()), false));
        baseViewHolder.setText(R.id.tv_home_find_read, String.valueOf(beanInfo.getScanCount()));
        baseViewHolder.setText(R.id.tv_home_find_reply, String.valueOf(beanInfo.getCommentCount()));

        headPortrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onFindClick != null) {
                    onFindClick.userInfo(beanInfo.getUserInfo().getUserId());
                }
            }
        });

        baseViewHolder.getView(R.id.rl_home_find_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onFindClick != null) {
                    onFindClick.details(beanInfo.getId());
                }
            }
        });

        baseViewHolder.getView(R.id.iv_home_find_image).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onFindClick != null) {
                    onFindClick.imageUrl(CommonConfiguration.splitResUrl(3, beanInfo.getSimpleImage()));
                }
            }
        });

        //关注作者
        ImageView isFollow = baseViewHolder.getView(R.id.tv_home_find_is_follow);
        UserFollow.setUserId(beanInfo.getCreateUser());
        if (mUserFollowList.contains(UserFollow)) {
            isFollow.setBackgroundResource(R.drawable.icon_follow_not);
            getData().get(baseViewHolder.getLayoutPosition()).setFollow(true);
        } else {
            isFollow.setBackgroundResource(R.drawable.icon_follow_yes);
            getData().get(baseViewHolder.getLayoutPosition()).setFollow(false);
        }

        isFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onFindClick != null) {
                    onFindClick.follow(beanInfo.getUserInfo().getUserId(), !beanInfo.getFollow());
//                    getData().get(baseViewHolder.getLayoutPosition()).setFollow(!beanInfo.getFollow());
//                    if (beanInfo.getFollow()) {
//                        isFollow.setBackgroundResource(R.drawable.icon_follow_not);
//                    } else {
//                        isFollow.setBackgroundResource(R.drawable.icon_follow_yes);
//                    }
                }
            }
        });

        //收藏文章
        TextView isCollect = baseViewHolder.getView(R.id.tv_home_find_collect);
        isCollect.setText(String.valueOf(beanInfo.getLikeCount()));
        articleCollect.setObjectId(beanInfo.getId());
        if (mUserArticleList.contains(articleCollect)) {
            isCollect.setCompoundDrawablesWithIntrinsicBounds(collectYes, null, null, null);
            getData().get(baseViewHolder.getLayoutPosition()).setCollect(true);
        } else {
            isCollect.setCompoundDrawablesWithIntrinsicBounds(collectNot, null, null, null);
            getData().get(baseViewHolder.getLayoutPosition()).setCollect(false);
        }

        isCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onFindClick != null) {
                    if (CommonConfiguration.isLogin(kv)) {
                        onFindClick.collect(beanInfo.getId(), !beanInfo.getCollect());
                        getData().get(baseViewHolder.getLayoutPosition()).setCollect(!beanInfo.getCollect());
                        if (beanInfo.getCollect()) {
                            isCollect.setCompoundDrawablesWithIntrinsicBounds(collectYes, null, null, null);

                            getData().get(baseViewHolder.getLayoutPosition()).setLikeCount(beanInfo.getLikeCount() + 1);
                            isCollect.setText(String.valueOf(beanInfo.getLikeCount()));
                        } else {
                            isCollect.setCompoundDrawablesWithIntrinsicBounds(collectNot, null, null, null);
                            getData().get(baseViewHolder.getLayoutPosition()).setLikeCount(beanInfo.getLikeCount() - 1);
                            isCollect.setText(String.valueOf(beanInfo.getLikeCount()));
                        }
                    } else {
//                        ToastUtils.showShort(getContext().getString(R.string.http_token_error));
                        LoginVerificationCodeActivity.start(getContext());
                    }
                }
            }
        });
    }

    public void setFollowState(List<CheckFollowListUserApi.BeanInfo> userFollowList) {
        mUserFollowList.clear();
        this.mUserFollowList = userFollowList;
        notifyDataSetChanged();
    }

    public void setArticleState(List<CheckCollectListUserApi.BeanInfo> userArticleList) {
        mUserArticleList.clear();
        this.mUserArticleList = userArticleList;
        notifyDataSetChanged();
    }

    public interface OnFindClick {
        void userInfo(String userId);

        void details(String articleId);

        void imageUrl(String url);

        void follow(String userId, boolean isFollow);

        void collect(String articleId, boolean isCollect);
    }
}
